package com.hsnn.medstgmini.common.interceptor;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class StdAttrPathInterceptor implements HandlerInterceptor {
	
	@Value("${file.path}")
	private String filePath;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		boolean bool = true;
		HttpServletRequest httpRequest = (HttpServletRequest) request;  
		HttpServletResponse httpResponse = (HttpServletResponse) response;  
		// 禁止缓存  
		httpResponse.setHeader("Cache-Control", "no-store");  
		httpResponse.setHeader("Pragrma", "no-cache");  
		httpResponse.setDateHeader("Expires", 0);  
		// 链接来源地址  
		String referer = httpRequest.getHeader("referer");  
		String serverName = httpRequest.getServerName();
		
		if (referer == null || !filePath.contains(serverName)) {  
			httpResponse.setHeader("Content-type", "text/html;charset=UTF-8");
			OutputStream os = response.getOutputStream();
			JSONObject returnMap = new JSONObject();// 封装返回信息
			returnMap.put("msg", "非站内请求");
			os.write(JSON.toJSONString(returnMap).getBytes("UTF-8"));
			os.flush();
			os.close();
			bool = false;
		} 
		return bool;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
